import axios from 'axios';
import { apiBaseUrl } from './config';

axios.defaults.baseURL = apiBaseUrl;
axios.defaults.timeout = 30000;

axios.interceptors.request.use(config => {
  // 在请求发出之前修改请求配置，在请求头中添加token、对参数加密
  if (config.url !== '/auth/authCode' && config.url !== '/administrator/checkloginByCode') {
    const token = sessionStorage.getItem('token');
    if (token) config.headers.Authorization = token;
  }
  return config;
}, err => Promise.reject(err));

axios.interceptors.response.use(res => {
  // 在响应回来之后，统一处理接口报错
  return res.data;
}, err => Promise.reject(err));

// 服务器响应返回的数据类型
interface IResponseData<T = any> {
  errCode: number;
  errMsg: string;
  data: T;
}

const get = (url: string, params = {}): Promise<IResponseData> => axios.get(url, { params });
const post = (url: string, data = {}): Promise<IResponseData> => axios.post(url, data);

export {
  get,
  post
};
